<?php
/**
 * Created by PhpStorm.
 * User: sunzexin
 * Date: 2018/1/6
 * Time: 11:25
 */

namespace App\Http\Logics\Admin;
use App\Captcha;

use App\Users;
use Illuminate\Support\Facades\Redis;
use App\Http\Logics\BaseLogic;
class CaptchaLogic extends BaseLogic
{
    /**
     * 创建验证码
     * @param $data 验证码信息
     * @return mixed 返回创建结果
     */
    public static function createCaptcha($data)
    {
        try{
            $response = self::getUserIdByLoginSession($data['loginSession']);
            if ($response->code){
                return self::response(self::CONTENT_IS_EMPTY);
            }
            $user_id = $response->data;
            $captcha = new Captcha();
            $captcha->user_id = $user_id;
            $captcha->mobile = $data['mobile'];
            $captcha->captcha=rand(1000,9999);
            if (!$captcha->save()){
                return self::response(self::OBJECT_SAVE_FAIL);
            }
            Redis::set($captcha->mobile, $captcha->captcha);
            Redis::expire($captcha->mobile, 300);
            $sms = json_decode(self::send_sms($captcha->mobile,$captcha->captcha));
            if ($sms->code){
                return self::response(self::SMS_SEND_FAILD);
            }
            return self::response(self::SUCCESS);
        }catch (\Exception $e){
            return self::response(self::SYSTEM_ERROR);
        }
    }

    /**
     * 验证短信验证码
     * @param $data 验证码信息
     * @return mixed 返回验证结果
     */
    public static function verifyCaptcha($data)
    {
        try{
            $response = self::getUserIdByLoginSession($data['loginSession']);
            if ($response->code){
                return self::response($response->code);
            }
            $user_id = $response->data;
            $captcha_value = Redis::get($data['mobile']);
            if (empty($captcha_value)){
                return self::response(self::CAPTCHA_IS_EXPIRE);
            }
            if ($data['captcha'] !== $captcha_value){
                return self::response(self::CAPTCHA_IS_WRONG);
            }
            if (Redis::del($data['mobile'])){
                $user = Users::find($user_id);
                $user->mobile = $data['mobile'];
                if (!$user->save()){
                    return self::response(self::OBJECT_SAVE_FAIL);
                }
                return self::response(self::SUCCESS);
            }
        }catch (\Exception $e){
            return self::response(self::SYSTEM_ERROR);
        }
    }
}